# -*- coding: utf-8 -*-
#!/usr/bin/env python
from django.http import HttpResponse
import json
import requests

def index(request):

    keyWord = request.POST.get("keyWord", "")

    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('scope', '103'),
        ('format', 'json'),
        ('appid', '379020'),
        ('bk_key', keyWord),
        ('bk_length', '600'),
    )

    num = 0
    while True:
        response = requests.get('http://baike.baidu.com/api/openapi/BaikeLemmaCardApi', headers=headers,
                                params=params).json()

        if "errno" in response.keys():

            num += 1
            if num == 10:
                response = {}
                break

            continue
        elif "id" in response.keys():
            break
        else:
            break

    response["type"] = 2

    return HttpResponse(json.dumps(response), content_type="application/json")
    # NB. Original query string below. It seems impossible to parse and
    # reproduce query strings 100% accurately so the one below is given
    # in case the reproduced version is not "correct".
    # response = requests.get('http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key=%E9%BB%91%E6%B4%9E&bk_length=600', headers=headers)


# index(1)